/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.filters;

import java.io.IOException;
import java.util.Collection;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.security.ActionPrivilegeMapping;

/**
 *
 * @author makcro
 */
public class SecurityFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        
        Object user = req.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);


        if (user == null) {
            String url = req.getContextPath() + "/default.do";
            res.sendRedirect(url);
        } else {


            //check if user has privileges to do requested operation
            Collection<Integer> privileges = (Collection<Integer>) req.getSession().getAttribute(ConstantManager.SESSION_USER_PRIVILEGES);
            String operationName = req.getParameter("method");
            //if user has clicked on link
            if (operationName != null) {
                ActionPrivilegeMapping actionPrivilegeMapping = new ActionPrivilegeMapping();
                Integer requiredPrivilage = actionPrivilegeMapping.getPrivilegeForAction(operationName);

                if (privileges.contains(requiredPrivilage)) {
                    chain.doFilter(request, response);
                } else {
                    String url = req.getContextPath() + "/forbidden.do";
                    res.sendRedirect(url);
                }
            }
            //if user has clicked on button than he is already allowed do execute operation
            else {
                chain.doFilter(request, response);
            }


        }
    }

    @Override
    public void destroy() {
    }
}
